const path = require('path');

const _ = require('../../tools/_');

const schema = require('./schema');

const col = db.collection('files');

module.exports = class Folder {
  constructor(info) {
    var self = this;

    _.extend(self, info, schema);
  }

  save() {
    var self = this;
    return new Promise((resolve, reject) => {
      var query = { name: self.name };

      self.folder && (query.folder = self.folder);
      mongo.findOne(col, { query }).then(doc => {

        if (doc) return reject(new Error('folder has been exists'));

        self.type = 'folder';
        mongo.insertOne(col, self).then(result => {
          self._id = result.insertedId;

          resolve(self);
        }).catch(reject);

      }).catch(reject);
    });
  }

  static find(_id) {
    return new Promise((resolve, reject) => {
      mongo.findOneByObjectId(col, _id).then(doc => {
        if (!doc) return reject(new Error('folder not found'));

        resolve(doc);
      }).catch(reject);
    });
  }
};
